package com.hxzy.common.interceptor.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.hxzy.common.annon.RepeatSubmit;
import com.hxzy.common.consts.RedisConst;
import com.hxzy.common.consts.UserConstants;
import com.hxzy.common.filter.RepeatedlyRequestWrapper;
import com.hxzy.common.interceptor.RepeatSubmitInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 功能描述
 *
 * @author tonneyyy
 */
@Component
public class UrlDataRepeatSubmitImpl extends RepeatSubmitInterceptor {
    public final String REPEAT_PARAMS = "repeatParams";

    public final String REPEAT_TIME = "repeatTime";

    @Autowired
    private RedisTemplate redisTemplate;

    @SuppressWarnings("unchecked")
    @Override
    public boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation)   {
        String nowParams = "";
        // 判断request是不是可重复读取的包装流   String -->   InputStream request.getInputStream()
        if (request instanceof RepeatedlyRequestWrapper) {
            RepeatedlyRequestWrapper repeatedlyRequest = (RepeatedlyRequestWrapper) request;
            try {
                nowParams = HttpUtil.getString(repeatedlyRequest.getInputStream(), Charset.forName("UTF-8"),false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // body参数为空，获取Parameter的数据
        if (StrUtil.isBlank(nowParams)) {
            nowParams = JSONObject.toJSONString(request.getParameterMap());
        }

        //构造一个可存放的数据 Map，存到redis中 String
        Map<String, Object> nowDataMap = new HashMap<String, Object>();
        // 把请求参数变为md5加密字符串 固定长度 32位   参数--》变为 CC6B895B4AC07E9E89D8CF42065691DF
        //nowDataMap.put(REPEAT_PARAMS, Md5Utils.md5Hex(nowParams) );
        nowDataMap.put(REPEAT_PARAMS, nowParams );
        //当前时间
        nowDataMap.put(REPEAT_TIME, System.currentTimeMillis());

        // *** 组装 redis的key ***********
        // 请求地址（作为存放cache的key值）      这个范围更广
        String url = request.getRequestURI();

        // 唯一值（没有消息头则使用请求地址）     当前用户
        String submitKey = request.getHeader(UserConstants.AUTHORIZATION_HEADER);
        if (StrUtil.isBlank(submitKey)) {
            submitKey = url;
        }

        // 唯一标识（指定key + 消息头）
        String cacheRepeatKey = RedisConst.REPEAT_SUBMIT_KEY + submitKey;

        //读取redis中String中的键
        Object sessionObj = redisTemplate.opsForValue().get(cacheRepeatKey);
        //如果redis中存在这个键
        if (sessionObj != null) {
            Map<String, Object> sessionMap = (Map<String, Object>) sessionObj;
            // 判断map中是否包含url
            if (sessionMap.containsKey(url)) {
                Map<String, Object> preDataMap = (Map<String, Object>) sessionMap.get(url);
                //比较 值   和  提交时间  是否过期
                if (compareParams(nowDataMap, preDataMap) && compareTime(nowDataMap, preDataMap, annotation.interval()))
                {
                    return true;
                }
            }
        }


        Map<String, Object> cacheMap = new HashMap<String, Object>();
        cacheMap.put(url, nowDataMap);

        // 存储到redis中,设定一个过期时间
        redisTemplate.opsForValue().set(cacheRepeatKey, cacheMap, annotation.interval(), TimeUnit.MILLISECONDS);
        return false;
    }

    /**
     * 判断参数是否相同
     */
    private boolean compareParams(Map<String, Object> nowMap, Map<String, Object> redisMap)
    {
        String nowParams = (String) nowMap.get(REPEAT_PARAMS);
        String preParams = (String) redisMap.get(REPEAT_PARAMS);
        return nowParams.equals(preParams);
    }

    /**
     * 判断两次间隔时间
     */
    private boolean compareTime(Map<String, Object> nowMap, Map<String, Object> redisMap, int interval)
    {
        long time1 = (Long) nowMap.get(REPEAT_TIME);
        long time2 = (Long) redisMap.get(REPEAT_TIME);
        if ((time1 - time2) < interval)
        {
            return true;
        }
        return false;
    }
}
